﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using DKE_Kinect.Entwicklung.PolyVox;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;

namespace DKE_Kinect.Entwicklung.Core
{
    /// <summary>
    /// Save and Load to a SavedGame Container
    /// </summary>
    public class SaveLoad
    {
       
      static  IAsyncResult result;
     //  static Object stateobj;
      /// <summary>
      /// is saveload working now
      /// </summary>
       static public bool Working = false;
  
          static BinaryFormatter pBFormatter=null;

          /// <summary>
          /// Gets the projects.
          /// </summary>
          static public String[] Projects
          {
              get { return SaveLoad.enumerate(); }
          }


          /// <summary>
          /// Saves the game file.
          /// </summary>
          /// <param name="filename">The filename.</param>
          /// <param name="p">The project.</param>
          /// <param name="r">The record.</param>
        public static void SaveGameFile(String filename,Projekt p,PolyVoxRecord r)
        {
            if (pBFormatter == null) { pBFormatter = new BinaryFormatter(); }
            result = StorageDevice.BeginShowSelector(
                             PlayerIndex.One, null, null);
            int count = 0;
            while (!result.IsCompleted) { count++; }
            StorageDevice device = StorageDevice.EndShowSelector(result);

            //not saving yet
            if (!Working)
            {
                Working = true;
                SaveLoad.DoSaveGame(device, filename, p,r);
                Working = false;
            }

        }

        /// <summary>
        /// Loads the game file.
        /// </summary>
        /// <param name="filename">The filename.</param>
        public static void LoadGameFile(String filename)
        {
            if (pBFormatter == null) { pBFormatter = new BinaryFormatter(); }
            result = StorageDevice.BeginShowSelector(
                             PlayerIndex.One, null, null);
            int count = 0;
            while (!result.IsCompleted) { count++; }
            StorageDevice device = StorageDevice.EndShowSelector(result);

            //not loading yet
            if (!Working)
            {
                Working = true;
                SaveLoad.DoLoadGame(device, filename);
                Working = false;
            }

        }
        private static String[] enumerate()
        {
           
            result = StorageDevice.BeginShowSelector(
                             PlayerIndex.One, null, null);
            int count = 0;
            while (!result.IsCompleted) { count++; }
            StorageDevice device = StorageDevice.EndShowSelector(result);
             String [] value = null;
            //not saving yet
            if (!Working)
            {
                Working = true;
                 value = SaveLoad.DoEnumerate(device);
                Working = false;
            }
            return value;

        }
        /// <summary>
        /// This method serializes a data object into
        /// the StorageContainer for this game.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="name">The name.</param>
        /// <param name="p">The project.</param>
        /// <param name="r">The record.</param>
        private static void DoSaveGame(StorageDevice device, String name, Projekt p, PolyVoxRecord r)
        {
            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("DKE_Kinect", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

           string filename = name+".sav";

           // Check to see whether the save exists.
           if (container.FileExists(filename))
              // Delete it so that we can create one fresh.
              container.DeleteFile(filename);

           // Create the file.
           Stream stream = container.OpenFile(filename,FileMode.OpenOrCreate);

           // Convert the object to XML data and put it in the stream.
        //   pBFormatter.Serialize(stream, p);
           pBFormatter.Serialize(stream, r);

           // Close the file.
           stream.Close();

           // Dispose the container, to commit changes.
           container.Dispose();

        }
        /// <summary>
        /// This method loads a serialized data object
        /// from the StorageContainer for this game.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="name">The name.</param>
        private static void DoLoadGame(StorageDevice device,String name)
        {
            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("DKE_Kinect", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            string filename = name+".sav";

            // Check to see whether the save exists.
            if (!container.FileExists(filename))
            {
               // If not, dispose of the container and return.
               container.Dispose();
               return;
            }

            // Open the file.
            Stream stream = container.OpenFile(filename, FileMode.Open);
            // Read the data from the file.
            Application.PolyvoxManager.LoadVolume(stream);

            // Close the file.
            stream.Close();

            // Dispose the container.
            container.Dispose();
            
 
        }
        
        /// <summary>
        /// This method illustrates how to enumerate files in a 
        /// StorageContainer.
        /// </summary>
        /// <param name="device"></param>
        private static String[] DoEnumerate(StorageDevice device)
        {
            IAsyncResult result =
                device.BeginOpenContainer("StorageDemo", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            String[] FileList = container.GetFileNames();

            // Dispose the container.
            container.Dispose();

            for (int i = 0; i < FileList.Length; i++)
            {
                FileList[i].Remove(FileList[i].Length - 4);
            }

            return FileList;
        }

        /// <summary>
        /// This method deletes a file previously created by this demo.
        /// </summary>
        /// <param name="device"></param>
        private static void DoDelete(StorageDevice device)
        {
            IAsyncResult result =
                device.BeginOpenContainer("StorageDemo", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            // Add the container path to our file name.
            string filename = "demobinary.sav";

            if (container.FileExists(filename))
            {
               container.DeleteFile(filename);
            }

            // Dispose the container, to commit the change.
            container.Dispose();
        }
       
    }

}
